package org.wltea.analyzer.help;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import java.util.function.Consumer;

import org.apache.logging.log4j.Logger;

public class JdbcHelper {

	private static final Logger logger = ESPluginLoggerFactory.getLogger(JdbcHelper.class.getName());

	private JdbcHelper() {
	}

	public static void executeDictSql(Properties properties, String sql, String updateSql,
			Consumer<ResultSet> consumer) {
		String driver = properties.getProperty("jdbc.driver");
		String url = properties.getProperty("jdbc.url");
		String user = properties.getProperty("jdbc.user");
		String password = properties.getProperty("jdbc.password");
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			Class.forName(driver);
			logger.info("driver init success......");
			connection = DriverManager.getConnection(url, user, password);
			logger.info(connection);
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
			logger.info("jdbc executeQuery success {}");
			consumer.accept(resultSet);
			statement.executeUpdate(updateSql);
			logger.info("jdbc executeUpdate success");
		} catch (ClassNotFoundException e) {
			logger.error("jdbcDriver is missing or not right");
		} catch (Throwable e) {
			logger.error("jdbc execute exception {}", e);
		} finally {
			try {
				if (resultSet != null) {
					resultSet.close();
				}
				if (statement != null) {
					statement.close();
				}
				if (connection != null) {
					connection.close();
				}
			} catch (SQLException e) {
				logger.error("jdbc close resource exception");
			}
		}
	}

}
